import 'dart:async';
import 'dart:math';

import 'package:app_30/home/fragment/vm/home_vm.dart';
import 'package:app_30/models/gogngao_entity.dart';
import 'package:app_30/models/load_entity.dart';
import 'package:app_30/models/vip_entity.dart';
import 'package:app_30/res/colors.dart';
import 'package:app_30/util/cache_utils.dart';
import 'package:app_30/widgets/marquee_flutter.dart';
import 'package:app_30/widgets/my_app_bar.dart';
import 'package:app_30/widgets/my_scroll_view.dart';
import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:stacked/stacked.dart';
import 'package:url_launcher/url_launcher.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  GonggaoEntity gongGao = getGonggao()!;
  String gonggao = Uri.decodeQueryComponent(getGonggao()!.gonggao!);

  LoadEntity? loadData = getLoadData();
  VipEntity? vipData = getVipData();
  String img = "";
  String vip = "";
  double addmoney = 0.0;

  int int1 = ((Random().nextDouble() * 9 + 1) * 1000).toInt();
  int int2 = getintRandom();
  int int3 = ((Random().nextDouble() * 9 + 1) * 1000).toInt();
  int int4 = getintRandom();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    AwesomeNotifications().isNotificationAllowed().then((isAllowed) {
      if (!isAllowed) {
        // Insert here your friendly dialog box before call the request method
        // This is very important to not harm the user experience
        AwesomeNotifications().requestPermissionToSendNotifications();
      }
    });

    AwesomeNotifications().actionStream.listen((receivedNotification) {});
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    if (loadData?.vip == "0") {
      vip = "普通会员";
    } else {
      vip = "VIP会员${loadData?.vip}";
    }
    ScrollController _controller = ScrollController();

    Timer(Duration(milliseconds: 500),
        () => _controller.jumpTo(_controller.position.maxScrollExtent));

    return ViewModelBuilder<HomeViewModel>.reactive(
        viewModelBuilder: () => HomeViewModel(),
        onModelReady: (viewModel) => viewModel.initialise(),
        builder: (context, viewModel, child) => Scaffold(
            appBar: MyAppBar(
              isBack: false,
              centerTitle: '首页',
            ),
            body: MyScrollView(
              children: [
                Padding(
                  padding: EdgeInsets.fromLTRB(15, 10, 15, 10),
                  child: Row(
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      Image.asset(
                        "assets/image/chat.png",
                        width: 16,
                        height: 14,
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Flexible(
                          child: Container(
                        width: double.infinity,
                        height: 24,
                        child: MarqueeWidget(
                          text:
                              "支付宝尾号:${int1}的用户成功提现余额${int2}元钱到账。      支付宝尾号：${int3}的用户成功提现推广奖励${int4}元钱到账。 提示：您做的每单佣金任务，在完成之后平台将会抽取您百分之二十的佣金作为技术费和商业税，你们赚取越多我们也赚的越多，合作共赢模式！感谢各位的信赖与支持！升级VIP会员做任务每单的佣金更高，每日佣金收益更多，提现金额无限制！       邀请好友您就可以获取到丰厚的现金奖励还可以升级终身VIP！详情可前往“分享界面”查看       ",
                          textStyle: new TextStyle(
                              fontSize: 14.0, color: Colors.black54),
                          scrollAxis: Axis.horizontal,
                        ),
                      ))
                    ],
                  ),
                ),
                SizedBox(
                  width: double.infinity,
                  height: 10,
                  child: Container(
                    color: Colors.black12,
                  ),
                ),
                Stack(
                  alignment: AlignmentDirectional.topCenter,
                  children: [
                    Align(
                      alignment: Alignment.center,
                      child: Container(
                        margin: EdgeInsets.fromLTRB(10, 20, 10, 10),
                        decoration: BoxDecoration(
                          color: Colours.app_main,
                          shape: BoxShape.rectangle,
                          borderRadius: BorderRadius.circular(5.0),
                        ),
                        child: Padding(
                          padding: EdgeInsets.fromLTRB(10, 15, 10, 1),
                          child: RichText(
                            softWrap: true,
                            text: TextSpan(
                              text: "${gonggao}",
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                    Align(
                      alignment: Alignment(0, 0),
                      child: Container(
                        margin: EdgeInsets.only(top: 10),
                        padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                        decoration: BoxDecoration(
                          color: Colors.black87,
                          shape: BoxShape.rectangle,
                          borderRadius: BorderRadius.circular(5.0),
                        ),
                        child: Padding(
                          padding: EdgeInsets.all(3),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text(
                                "官方公告",
                                textAlign: TextAlign.left,
                                style: TextStyle(
                                  fontSize: 13,
                                  color: Colors.white,
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                    )
                  ],
                ),
                SizedBox(
                  width: double.infinity,
                  height: 10,
                  child: Container(
                    color: Colors.black12,
                  ),
                ),
                Padding(
                  padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
                  child: Row(mainAxisSize: MainAxisSize.max, children: [
                    Expanded(
                      child: SizedBox(
                        height: 160,
                        child: Container(
                          padding: EdgeInsets.all(5),
                          child: viewModel.bytes != null
                              ? Image.memory(
                                  viewModel.bytes!,
                                  height: 30, //设置高度
                                  width: 70, //设置宽度
                                  fit: BoxFit.fitHeight, //填充
                                  gaplessPlayback: true, //防止重绘
                                )
                              : Image.asset(
                                  "${viewModel.assetImg}",
                                  fit: BoxFit.fitHeight,
                                ),

                          // LoadAssetImage(
                          //         '${viewModel.img}',
                          //         width: 80,
                          //         height: 80,
                          //       ),
                        ),
                      ),
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    Expanded(
                      child: // use Spacer
                          SizedBox(
                        height: 160,
                        child: Container(
                          padding: EdgeInsets.all(5),
                          color: Colors.black87,
                          child: ListView.builder(
                            controller: _controller,
                            itemBuilder: (BuildContext context, int index) {
                              String data = viewModel.data[index];
                              return Container(
                                alignment: Alignment.centerLeft,
                                child: Column(
                                  children: [
                                    Text('${data}',
                                        style: TextStyle(
                                            color: Colours.app_main,
                                            fontSize: 12))
                                  ],
                                ),
                              );
                            },
                            itemCount: viewModel.data.length,
                          ),
                        ),
                      ),
                    ),
                  ]),
                ),
                Padding(
                  padding: EdgeInsets.fromLTRB(15, 5, 15, 5),
                  child: Row(mainAxisSize: MainAxisSize.max, children: [
                    Expanded(
                        child: SizedBox(
                      height: 40,
                      child: TextButton(
                        child: Text(viewModel.isStart ? "结束运行" : "开始运行"),
                        //添加一个点击事件
                        onPressed: () {
                          viewModel.change();
                        },
                        //设置按钮是否自动获取焦点
                        autofocus: true,
                        //定义一下文本样式
                        style: buildButtonStyle(),
                      ),
                    )),
                    SizedBox(
                      width: 10,
                    ),
                    Expanded(
                        child: // use Spacer
                            SizedBox(
                      height: 40,
                      child: TextButton(
                        child: Text("官方网站"),
                        //添加一个点击事件
                        onPressed: () {
                          launch('${gongGao.jcurl}');
                        },
                        //设置按钮是否自动获取焦点
                        autofocus: true,
                        //定义一下文本样式
                        style: buildButtonStyle(),
                      ),
                    )),
                  ]),
                ),
                SizedBox(
                  width: double.infinity,
                  height: 10,
                  child: Container(
                    color: Colors.black12,
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                  child: Column(
                    children: [
                      Row(mainAxisSize: MainAxisSize.max, children: [
                        buildBlackText("用户名", Colors.black87),
                        const SizedBox(
                          width: 3,
                        ),
                        buildBlackText("账户余额", Colors.black87),
                        const SizedBox(
                          width: 3,
                        ),
                        buildBlackText("会员类型", Colors.black87),
                      ]),
                      const SizedBox(
                        height: 1.5,
                      ),
                      Row(mainAxisSize: MainAxisSize.max, children: [
                        buildBlackText("${getUser()}", Colors.black54),
                        const SizedBox(
                          width: 3,
                        ),
                        buildBlackText(
                            "${viewModel.allMoney.toStringAsFixed(2)}",
                            Colors.black54),
                        const SizedBox(
                          width: 3,
                        ),
                        buildBlackText("${vip}", Colors.black54),
                      ]),
                    ],
                  ),
                )
              ],
            )));
  }

  Expanded buildBlackText(text, color) {
    return Expanded(
      child: Container(
        padding: EdgeInsets.fromLTRB(2, 0, 3, 0),
        decoration: BoxDecoration(
          color: color,
          shape: BoxShape.rectangle,
          borderRadius: BorderRadius.circular(5.0),
        ),
        child: Padding(
          padding: EdgeInsets.all(2),
          child: Expanded(
            child: Text(
              text,
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 14, color: Colors.white),
            ),
          ),
        ),
      ),
    );
  }

  ButtonStyle buildButtonStyle() {
    return ButtonStyle(
      //定义文本的样式 这里设置的颜色是不起作用的
      textStyle: MaterialStateProperty.all(
          TextStyle(fontSize: 15, color: Colours.app_main)),
      //设置按钮上字体与图标的颜色
      //foregroundColor: MaterialStateProperty.all(Colors.deepPurple),
      //更优美的方式来设置
      foregroundColor: MaterialStateProperty.resolveWith(
        (states) {
          if (states.contains(MaterialState.focused) &&
              !states.contains(MaterialState.pressed)) {
            //获取焦点时的颜色
            return Colors.white;
          } else if (states.contains(MaterialState.pressed)) {
            //按下时的颜色
            return Colors.white70;
          }
          //默认状态使用灰色
          return Colors.white;
        },
      ),
      //背景颜色
      backgroundColor: MaterialStateProperty.resolveWith((states) {
        //设置按下时的背景颜色
        if (states.contains(MaterialState.pressed)) {
          return Colours.dark_app_main;
        }
        //默认不使用背景颜色
        return Colours.app_main;
      }),
      //设置水波纹颜色
      overlayColor: MaterialStateProperty.all(Colours.app_main),
      //设置阴影  不适用于这里的TextButton
      elevation: MaterialStateProperty.all(0),
      //设置按钮内边距
      padding: MaterialStateProperty.all(EdgeInsets.zero),
      //设置按钮的大小
      // minimumSize: MaterialStateProperty.all(Size(double.infinity, 20)),
      //设置边框
      // side: MaterialStateProperty.all(BorderSide(color: Colors.grey, width: 1)),
      //外边框装饰 会覆盖 side 配置的样式
      // shape: MaterialStateProperty.all(StadiumBorder()),
    );
  }
}

int getintRandom() {
  int max = 2000;
  int min = 50;
  return Random().nextInt(max - min) + min;
}
